package com.fenfen.novel;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.fenfen.novel.fragment.NovelCategoryFragment;
import com.fenfen.novel.fragment.NovelListFragment;
import com.fenfen.novel.fragment.NovelReadLogFragment;
import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.SharedPrefsUtils;

public class MainActivity extends BaseActivity {

  private static String Tag = MainActivity.class.getSimpleName();

  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide
   * fragments for each of the sections. We use a
   * {@link FragmentPagerAdapter} derivative, which will keep every
   * loaded fragment in memory. If this becomes too memory intensive, it
   * may be best to switch to a
   * {@link android.support.v4.app.FragmentStatePagerAdapter}.
   */
  private SectionsPagerAdapter mSectionsPagerAdapter;

  /**
   * The {@link ViewPager} that will host the section contents.
   */
  private ViewPager mViewPager;
  private Spinner topTypeSpinner;
  private byte currentTopType;

  private ActionMode mActionMode;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initToolbar();

    topTypeSpinner = (Spinner) findViewById(R.id.top_type_spinner);
    if (topTypeSpinner != null) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        CommonUtil.filterDrawableColor(this, topTypeSpinner.getPopupBackground(), R.attr.colorPrimary);
      } else {
        CommonUtil.filterDrawableColor(this, topTypeSpinner.getBackground(), R.attr.colorPrimary);
      }
    }
    ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.top_type_array, R.layout.spinner_item);
    spinnerAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
    topTypeSpinner.setAdapter(spinnerAdapter);
    topTypeSpinner.setOnItemSelectedListener(new TopTypeSpinnerChangeListener());

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(2);
    mViewPager.addOnPageChangeListener(new ViewPagerPageChangeListener());

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

  }

  private void initToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item = menu.findItem(R.id.action_night);
    boolean isNight = SharedPrefsUtils.getInstance(this).getChapterNightMode();
    item.setTitle(isNight ? R.string.day_mode : R.string.night_mode);
    return super.onPrepareOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
      case R.id.action_search:
        Intent intent = new Intent(this, SearchNovelActivity.class);
        startActivity(intent);
        break;
      case R.id.action_night:
        notifyAllChangeTheme();
        break;
      case R.id.action_settings:
        startActivity(new Intent(this, SettingActivity.class));
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  public void setActionMode(ActionMode mActionMode) {
    this.mActionMode = mActionMode;
  }

  public ActionMode getActionMode() {
    return mActionMode;
  }

  public void cancelActionMode() {
    if (mActionMode != null) {
      mActionMode.finish();
      mActionMode = null;
    }
  }

  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
   * one of the sections/tabs/pages.
   */
  public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
    Fragment topFragment;

    public SectionsPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
      super.setPrimaryItem(container, position, object);
      topFragment = (Fragment) object;
      switch (position) {
        case 1:
          final NovelCategoryFragment fragment = (NovelCategoryFragment) object;
          if (!fragment.isLoading() && !fragment.hasData()) {
            CommonUtil.showSnackRetry(fragment.getView(), R.string.get_category_error, new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                fragment.loadData();
              }
            });
          }
          if (fragment.isLoading()) {
            Snackbar.make(fragment.getView(), R.string.loading, Snackbar.LENGTH_LONG);
          }
          break;
        default:
          break;
      }
    }

    @Override
    public Fragment getItem(int position) {
      // getItem is called to instantiate the fragment for the given page.
      Fragment fragment = null;
      switch (position) {
        case 0:
          currentTopType = getTopTypeByPosition(topTypeSpinner.getSelectedItemPosition());
          Log.d(Tag, "init top type=" + currentTopType);
          Bundle bundle = new Bundle();
          bundle.putByte(NovelListFragment.EXTRA_DATA_TYPE, CommonUtil.NovelListType.TYPE_NOVEL_TOP);
          bundle.putByte(NovelListFragment.EXTRA_TOP_TYPE, currentTopType);
          fragment = NovelListFragment.newInstance(bundle);
          break;
        case 1:
          fragment = NovelCategoryFragment.newInstance(null);
          break;
        case 2:
          fragment = NovelReadLogFragment.newInstance(null);
          break;
      }
      return fragment;
    }

    @Override
    public int getCount() {
      // Show 3 total pages.
      return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      switch (position) {
        case 0:
          return getResources().getString(R.string.tab_ranking);
        case 1:
          return getResources().getString(R.string.tab_category);
        case 2:
          return getResources().getString(R.string.tab_read_record);
      }
      return null;
    }
  }

  private class TopTypeSpinnerChangeListener implements android.widget.AdapterView.OnItemSelectedListener {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      byte topType = getTopTypeByPosition(position);
      currentTopType = topType;
      //update first fragment with currentTopType
      Fragment topFragment = mSectionsPagerAdapter.topFragment;
      if (topFragment != null && topFragment instanceof NovelListFragment) {
        NovelListFragment listFragment = (NovelListFragment) topFragment;
        if (listFragment.getTopType() != 0 && listFragment.getTopType() != currentTopType) {
          Log.d(Tag, "select item,old top type=" + listFragment.getTopType() + ",new top type=" + currentTopType);
          listFragment.setTopType(currentTopType);
//          listFragment.loadNovelTopList(currentTopType);
          listFragment.loadData();
        }
      }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
  }

  private byte getTopTypeByPosition(int position) {
    return CommonUtil.TOPTYPE[position];
  }

  private class ViewPagerPageChangeListener implements ViewPager.OnPageChangeListener {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
      if (position == 0) {
        //show spinner
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        topTypeSpinner.setVisibility(View.VISIBLE);
      } else {
        //dismiss spinner
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        topTypeSpinner.setVisibility(View.GONE);
      }
      if(position != 2) {
        cancelActionMode();
      }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
  }
}
